﻿namespace PropOnline.Security
{
    using System;
    using System.Linq;
    using System.Web;
    using PropOnline.Stores.Data;

    public class AutenticationModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.PostAuthenticateRequest += this.Context_PostAuthenticateRequest;
        }

        private void Context_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var username = HttpContext.Current.User.Identity.Name;

            if (!string.IsNullOrWhiteSpace(username))
            {
                int idUsuario = -1;
                int.TryParse(username, out idUsuario);
                var usuario =
                    Database
                        .Query("Select * From usuario Where usuario.Id = ?idUsuario")
                        .WithParameter("?idUsuario", idUsuario)
                        .Results()
                        .SingleOrDefault();

                if (usuario == null || string.IsNullOrWhiteSpace(usuario.Inmobiliaria))
                {
                    System.Web.Security.FormsAuthentication.SignOut();
                    System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                }
            }
        }
    }
}